import { Component, Input, OnInit } from '@angular/core';
import { NzMessageService, NzModalRef } from 'ng-zorro-antd';
import * as moment from 'moment';
import { FetchService } from '../../../../core/net/fetch.service';
import { FormBuilder, FormGroup } from '@angular/forms';
import { format, startOfMonth, endOfMonth, subMonths, subDays } from 'date-fns';
import * as _ from 'lodash';

@Component({
    selector: 'app-gate-control-detail',
    templateUrl: './gate-control-detail.component.html',
    styleUrls: ['./gate-control-detail.component.scss']
})
export class GateControlDetailComponent implements OnInit {
    @Input() data: any;
    tabRange = {
        '最近24小时': [new Date(), new Date()],
        '最近一周': [subDays(new Date(), 7), new Date()],
        '最近一月': [subMonths(new Date(), 1), new Date()]
    };
    isChartContent = true;  //  水位流量过程线内容类型 是否为图表
    waterTableData = [];
    pageNum = 1;
    pageSize = 10;
    tabDateRange = [new Date(), new Date()];
    baseWaterChartOpt: any = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
                animation: false,
                label: {
                    backgroundColor: '#505765'
                }
            }
        },
        color: ['#289df5', '#046351'],
        legend: {
            data: ['闸前', '闸后'],
            bottom: 10
        },
        xAxis: {
            type: 'category',
            data: []
        },
        yAxis: [
            {
                name: '水位(m)',
                type: 'value'
            }
        ],
        series: [
            {
                name: '闸前水位',
                type: 'line',
                smooth: true,
                data: []
            },
            {
                name: '闸后水位',
                type: 'line',
                smooth: true,
                data: []
            }
        ]
    };
    baseFlowChartOpt = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
                animation: false,
                label: {
                    backgroundColor: '#505765'
                }
            }
        },
        color: ['#289df5', '#fbc01b'],
        legend: {
            data: ['流量'],
            bottom: 10
        },
        xAxis: {
            type: 'category',
            data: []
        },
        yAxis: [
            {
                name: '流量(m³/s)',
                type: 'value'
            }
        ],
        series: [
            {
                name: '流量',
                type: 'line',
                smooth: true,
                data: []
            }
        ]
    };
    baseDegreeChartOpt = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
                animation: false,
                label: {
                    backgroundColor: '#505765'
                }
            }
        },
        color: ['#f5c239'],
        legend: {
            data: ['开度'],
            bottom: 10
        },
        xAxis: {
            type: 'category',
            data: []
        },
        yAxis: [
            {
                name: '开度(mm)',
                type: 'value'
            }
        ],
        series: [
            {
                name: '开度',
                type: 'line',
                smooth: true,
                data: []
            }
        ]
    };
    lineOpt1 = {};
    lineOpt2 = {};
    lineOpt3 = {};
    /***************** 闸门控制 ******************/
    isHistoryContent = false;
    pageHistoryNum = 1;
    historyTableData = [];
    /***************** 闸门示意图 ******************/
    degreeDetail = 0;
    gateHeight: number = 1;
    /**********  闸门控制  ************/
    flowCtrlForm: FormGroup;
    openingCtrlForm: FormGroup;
    // formatterMinutes = (value: number) => `${value} 分钟`;
    // formatterMM = (value: number) => `${value} mm`;
    // formatterFlow = (value: number) => `${value} m³/s`;
    // parserFlow = (value: string) => value.replace(' m³/s', '');
    // parserMinutes = (value: string) => value.replace(' 分钟', '');
    // parserMM = (value: string) => value.replace(' mm', '');

    constructor(private modal: NzModalRef,
                private fb: FormBuilder,
                private message: NzMessageService,
                private fetchService: FetchService) {
        this.flowCtrlForm = this.fb.group({
            value: [''],
            controlTime: ['']
        });
        this.openingCtrlForm = this.fb.group({
            value: [''],
            controlTime: ['']
        });
    }

    ngOnInit(): void {
        // console.log(this.data);
        this.getProcessListGate();
        this.getGateSketchData();
        this.queryHistoryInfo();
    }

    onTabDateChange(date): void {
        this.getProcessListGate();
    }

    /**
     * 获取闸门示意图数据
     */
    getGateSketchData(): void {
        this.degreeDetail = parseFloat(this.data.degree);
        this.gateHeight = parseFloat(this.data.strobeOpenHeight);
    }
    /**
     * 获取当前闸门 水位流量过程线 默认查询当天数据
     */
    getProcessListGate() {
        this.fetchService.post(
            'base/wrsBrwaterDam/queryProcessLinList',
            {
                stadiaCode: this.data.stadiaCode,
                beginTime: moment(this.tabDateRange[0]).format('YYYY-MM-DD'),
                endTime: moment(this.tabDateRange[1]).format('YYYY-MM-DD'),
                pageSize: 100000
            }
        ).subscribe(res => {
            const list = res['list'];
            this.waterTableData = res['list'];
            this.lineOpt1 = {
                legend: {
                    data: ['闸前水位', '闸后水位'],
                    bottom: 10
                },
                xAxis: [
                    {
                        data: this.getItemValues(list, 'meaTime')
                    }
                ],
                series: [
                    {
                        name: '闸前水位',
                        data: this.getItemValues(list, 'heightUp')
                    },
                    {
                        name: '闸后水位',
                        data: this.getItemValues(list, 'heightDown')
                    }
                ]
            };
            this.lineOpt2 = {
                legend: {
                    data: ['流量'],
                    bottom: 10
                },
                xAxis: [
                    {
                        data: this.getItemValues(list, 'meaTime')
                    }
                ],
                series: [
                    {
                        data: this.getItemValues(list, 'flux')
                    }
                ]
            };
            this.lineOpt3 = {
                legend: {
                    data: ['开度'],
                    bottom: 10
                },
                xAxis: [
                    {
                        data: this.getItemValues(list, 'meaTime')
                    }
                ],
                series: [
                    {
                        data: this.getItemValues(list, 'degree')
                    }
                ]
            };
        });
    }
    /**
     *  切换闸门开关闸记录列表
     */
    toggleHistoryContent(): void {
        this.isHistoryContent = !this.isHistoryContent;
    }
    /**
     *  切换水位流量过程线 图表和列表 形式
     */
    toggleTabContent(): void {
        this.isChartContent = !this.isChartContent;
    }
    operateGate(model: string): void {
        const params = {
            strobeId: this.data.strobeId,
            // strobeId: '306',
            model: model,
            value: model === 'model2' ? this.openingCtrlForm.value.value : this.flowCtrlForm.value.value,
            controlTime: model === 'model2' ? this.openingCtrlForm.value.controlTime : this.flowCtrlForm.value.controlTime
        };
        this.fetchService.post('base/wrsBawaterGateControl/control', params).subscribe(res => {
            if (res) {
                this.message.success('操作成功');
            } else {
                this.message.error('操作失败');
            }
        });
    }

    /**
     *  开关闸历史记录
     */
    queryHistoryInfo(): void {
        const params = {
            pageNum: this.pageHistoryNum,
            pageSize: this.pageSize
        };
        this.fetchService.post('base/wrsBawaterGateControl/list', params).subscribe(res => {
            this.historyTableData = res['list'];
        });
    }
    private getItemValues(list, key) {
        return list.map(i => {
            return i[key] || 0;
        });
    }
}
